package cn.shop.front.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.shop.front.entity.Feedback;
import cn.shop.front.entity.req.FeedbackQueryReq;
import cn.shop.front.service.FeedbackService;
import cn.shop.front.util.CurrentUserUtil;
import cn.shop.thiredparty.config.OSSConfig;
import cn.shop.thiredparty.entity.Metadata;
import cn.shop.thiredparty.service.AliOssService;
import cn.shop.utils.ApiResult;
import cn.shop.utils.PageUtil;
import cn.shop.utils.Putif;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author : 李一涵
 * @date : Created in 2022/9/7 15:14
 * @description :
 */
@RestController
@RequestMapping("/api/v1/feedback")
public class FeedbackController {

    @Resource
    private AliOssService ossService;
    @Resource
    private OSSConfig config;
    @Resource
    private FeedbackService feedbackService;

    @GetMapping("/categories")
    public ApiResult<List<String>> categories() {
        List<String> list = Arrays.asList("充值", "购买", "提现", "寄售");
        return ApiResult.success(list);
    }

    @SaCheckLogin
    @PostMapping("")
    public ApiResult<Map<String, Object>> addFeedback(@Validated @RequestBody Feedback feedback) {
        long userId = CurrentUserUtil.getUserId();
        feedback.setUserId(userId);
        return ApiResult.result(feedbackService.save(feedback));
    }

    @SaCheckLogin
    @GetMapping("/list")
    public ApiResult<Map<String, Object>> feedbacks(@Validated FeedbackQueryReq req) {
        long userId = CurrentUserUtil.getUserId();
        Page<Feedback> page = Page.of(req.getCurrent(), req.getSize());
        LambdaQueryWrapper<Feedback> query = Wrappers.<Feedback>lambdaQuery()
                .eq(Feedback::getUserId, userId)
                .gt(req.getStartTime() != null, Feedback::getCreateTime, req.getStartTime())
                .lt(req.getEndTime() != null, Feedback::getCreateTime, req.getEndTime())
                .orderByDesc(Feedback::getUpdateTime);
        page = feedbackService.page(page, query);
        Map<String, Object> data = PageUtil.formatPage(page, feedback -> Putif.start()
                        .anyway("category", feedback.getCategory())
                        .anyway("content", feedback.getContent())
                        .anyway("img", feedback.getImg() != null ? config.getPrefix() + "/" + feedback.getImg() : "")
                        .anyway("time", feedback.getCreateTime()).get()
        );
        return ApiResult.success(data);
    }

    /**
     * 上传图片接口
     *
     * @param files 要上传的图片
     * @return 返回结果
     */
    @PostMapping("/upload")
    public ApiResult<List<Map<String, String>>> upload(@RequestParam MultipartFile[] files){
        List<Map<String, String>> list = new LinkedList<>();
        for(MultipartFile file : files){
            Map<String, String> model = new LinkedHashMap<>();
            //不是图片的处理
            if(!isImage(file.getOriginalFilename())){
                model.put("flag","false");
                model.put("msg", "文件不是图片");
                model.put("file", file.getOriginalFilename());
                list.add(model);
                continue;
            }

            //图片大小不超过5MB
            if(file.getSize()/1024/1024 >= 5){
                model.put("flag","false");
                model.put("msg", "图片大小不能超过5M");
                model.put("file", file.getOriginalFilename());
                list.add(model);
                continue;
            }
            Metadata metadata = new Metadata();
            metadata.setFilename(file.getOriginalFilename());
            metadata.setContentType(file.getContentType());
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

            String filename = ossService.upload(metadata, inputStream);
            model.put("flag","true");
            model.put("filename", filename);
            model.put("fileUrl", config.getPrefix() + "/" + filename);
            list.add(model);
        }
        return ApiResult.success(list);
    }

    private boolean isImage(String originalFilename) {
        if (originalFilename == null)
            return false;
        if(originalFilename.contains(".")){
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileExt = fileExt.toLowerCase();
            return fileExt.equals(".jpg")
                    || fileExt.equals(".jpeg")
                    || fileExt.equals(".gif")
                    || fileExt.equals(".png")
                    || fileExt.equals(".bmp");
        }
        return false;
    }
}
